<?php

class PreviewController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
  public $slogan;
  public $code;
  
  	/**
	 * @var const Indica el numero de registros por defecto en un listado.
	 */
	const PAGE_SIZE=1;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','page','blogEntry','new','image'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function init()
  {
           
          parent::init();
  }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
    
    $this->render('index',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	/**
	 * Displays a particular site with your template.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionviewSite($id)
	{
		
    
    $this->render('index',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Site;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Site']))
		{
			$model->attributes=$_POST['Site'];
			
			if($model->save()){			   
			   $this->redirect(array('admin'));
    }			  
				
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Site']))
		{
			$model->attributes=$_POST['Site'];
		
			if($model->save())
				$this->redirect(array('view','id'=>$model->sit_code));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
    
		$model=Site::model()->findByPk($_GET['id']);
	   //valida si el usuario es dueño del sitio
    $this->isOwner($model->sit_code);
    
		$this->changeTemplate($model->sit_code);
    $this->pageTitle = $model->sit_title;
    $this->slogan = $model->sit_slogan;
    $this->code = $model->sit_code;
		$this->render('index',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Lists all models.
	 */
	public function actionPage()
	{	  
	 
		$model=Page::model()->findByPk($_GET['id']);
		//valida si el usuario es dueño del sitio
    $this->isOwner($model->sit_code);
	  $this->changeTemplate($model->sit_code);
	  
		switch($model->pag_type){      
        case 'content':
          $this->contentPage($model);
        break;
        case 'blog':
          $this->blogPage($model);
        break;
        case 'news':
          $this->newsPage($model);
        break;
        case 'gallery':
          $this->galleryPage($model);
        break;
        case 'contact':
          $this->contactPage($model);
        break;
    }
	}
	
	
	private function contentPage($model)
	{      
    $this->getSiteParametres($model->sit_code);
		$this->render('content',array(
			'model'=>$model,
		));
  }
  
  private function blogPage($model)
	{ 
    Yii::import('application.helpers.CString');     
    $this->getSiteParametres($model->sit_code);
    
    if($model->pag_title != "")
      $this->pageTitle=$model->pag_title;
      
    $criteria=new CDbCriteria;
    $criteria->params = array(':pag_code'=>$model->pag_code);
    $criteria->condition = 'pag_code=:pag_code';
    $pages=new CPagination(BlogEntry::model()->count($criteria));
    $pages->setPageSize(self::PAGE_SIZE);
    $pages->applyLimit($criteria);
    $models=BlogEntry::model()->findAll($criteria);
  

	$this->render('blog', array(
		'item_count'=>$item_count,
		'page_size'=>$page_size,
		'items_count'=>$item_count,
		'pages'=>$pages,
		'sample'=>$sample,
		'model'=>$models
	));  
		
  }
  
  private function newsPage($model)
	{ 
      Yii::import('application.helpers.CString');     
      $this->getSiteParametres($model->sit_code);
      
      if($model->pag_title != "")
        $this->pageTitle=$model->pag_title;
        
      $criteria=new CDbCriteria;
      $criteria->params = array(':pag_code'=>$model->pag_code);
      $criteria->condition = 'pag_code=:pag_code';
      $pages=new CPagination(NewItem::model()->count($criteria));
      $pages->pageSize=self::PAGE_SIZE;
      $pages->applyLimit($criteria);
      $models=NewItem::model()->findAll($criteria);
    
     
  	$this->render('new', array(
  		'item_count'=>$item_count,
  		'page_size'=>$page_size,
  		'items_count'=>$item_count,
  		'pages'=>$pages,
  		'sample'=>$sample,
  		'model'=>$models,
  		'page'=>$model
  		
  	));  
		
  }
  
  
  private function galleryPage($model)
	{                 
      $this->getSiteParametres($model->sit_code);
          
      if($model->pag_title != "")
        $this->pageTitle=$model->pag_title;
        
      $criteria=new CDbCriteria;
      $criteria->params = array(':pag_code'=>$model->pag_code);
      $criteria->condition = 'pag_code=:pag_code';
      
      $pages=new CPagination(Gallery::model()->count($criteria));
      $pages->pageSize=self::PAGE_SIZE;
      $pages->applyLimit($criteria);
      $models=Gallery::model()->findAll($criteria);
       
     
  	$this->render('gallery', array(
  		'item_count'=>$item_count,
  		'page_size'=>$page_size,
  		'items_count'=>$item_count,
  		'pages'=>$pages,
  		'sample'=>$sample,
  		'model'=>$models,
  		'page'=>$model  		
  		
  	));  
		
  }
  
  private function contactPage($model)
	{                 
      $this->getSiteParametres($model->sit_code);
          
      if($model->pag_title != "")
        $this->pageTitle=$model->pag_title;
        
      $criteria=new CDbCriteria;
      $criteria->params = array(':pag_code'=>$model->pag_code);
      $criteria->condition = 'pag_code=:pag_code';
      $models=Contact::model()->find($criteria);
      Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.'/js/jquery.validate.min.js'); 
     
    	$this->render('contact', array(
    		'item_count'=>$item_count,
    		'page_size'=>$page_size,
    		'items_count'=>$item_count,
    		'pages'=>$pages,
    		'sample'=>$sample,
    		'model'=>$models,
    		'page'=>$model  		
    		
    	));  
		
  }
  
  /**
	 * Lists all models.
	 */
	public function actionImage()
	{	  
	  if (Yii::app()->user->isGuest) {
            Yii::app()->theme = 'cleary';
    } else {            
            Yii::app()->theme = 'cleary';
    } 
    
    $criteria=new CDbCriteria;
    $criteria->params = array(':gal_code'=>(int)$_GET['id']);
    $criteria->condition = 'gal_code=:gal_code';
    
    $model=Gallery::model()->findByPk((int)$_GET['id']);
    
    $pages=new CPagination(Image::model()->count($criteria));
    $pages->setPageSize(self::PAGE_SIZE);
    $pages->applyLimit($criteria);
    $models=Image::model()->findAll($criteria);
  
    $this->getSiteParametres($model->pagCode->sitCode->sit_code);
	$this->render('image', array(
		'item_count'=>$item_count,
		'page_size'=>$page_size,
		'items_count'=>$item_count,
		'pages'=>$pages,
		'sample'=>$sample,
		'model'=>$models
	));  
    
    		
		
	}
  
  /**
	 * Lists all models.
	 */
	public function actionBlogEntry()
	{	  
	  if (Yii::app()->user->isGuest) {
            Yii::app()->theme = 'cleary';
    } else {            
            Yii::app()->theme = 'cleary';
    } 
    
		$model=BlogEntry::model()->findByPk($_GET['id']);
		$this->getSiteParametres($model->pagCode->sitCode->sit_code);
		$this->render('blogEntry',array(
			'model'=>$model,
		));
		
	}
	
	/**
	 * Lists all models.
	 */
	public function actionNew()
	{	  
	  if (Yii::app()->user->isGuest) {
            Yii::app()->theme = 'cleary';
    } else {            
            Yii::app()->theme = 'cleary';
    } 
    
		$model=NewItem::model()->findByPk($_GET['id']);
		$this->getSiteParametres($model->pagCode->sitCode->sit_code);
		$this->render('newEntry',array(
			'model'=>$model,
		));
		
	}
  
  
  
  private function getSiteParametres($siteCode)
  {
    $site=Site::model()->findByPk($siteCode);
    $this->pageTitle = $site->sit_title;
    $this->slogan = $site->sit_slogan;
    $this->code = $site->sit_code;
  }

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Site('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Site']))
			$model->attributes=$_GET['Site'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Site::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='site-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
  /**
	 * Inicializa la vista (theme)
	 * @param id codigo del sitio	 
	 */	                         
                    
	private function changeTemplate($id){
	  $model=Site::model()->findByPk($id);
	  if($model){
      Yii::app()->theme = $model->template->tem_name;
      Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl.'/js/jquery-1.5.min.js');
    }
    else
      	throw new CHttpException(404,'The requested page does not exist.');  
  }
	
	/**
	 * Crea un field de formulario de acuerdo a los parametros datos para que se
	 * validado con jquery validate	 
	 * @param type tipo de campo (text,textarea)
	 * @param validate tipo de validacion sobre el campo (email,url..)
	 * @param requerid si el campo es requerido o no
	 * @param value valor por defecto del campo      	 
	 */
	public function makeField($type='text',$validate='text',$requerid=false,$value="",$name=''){
	
	  $requeridValue='';
	  if((boolean)$requerid === true){
      $requeridValue='requerid';
    }
    
    switch($validate){
      case 'email':
        $validateText='email';
      break;
      case 'url':
        $validateText='url';
      break;
      case 'number':
        $validateText='digit';
      break;
      default:
        $validateText='';
      break;
    }
    
    switch($type){
      case 'text':
        return '<input type="text" name="'.$name.'" value="'.$value.'" class="'.$requeridValue.' '.$validateText.'" data-role="none" />';
      break;
      case 'textarea':
        return '<textarea class="'.$requeridValue.' '.$validateText.'" name="'.$name.'" id="ccomment" data-role="none" cols="40" rows="8">'.$value.'</textarea>';
      break;
    }
  
  }
  
  
   private function isOwner($siteCode=0)
	 {      
      $model=Site::model()->findByPk($siteCode);
      if(!Site::model()->isOwner($siteCode))                         
            	throw new CHttpException(404,'The requested page does not have acces.');
        
    }
}
